// ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:mybase/base/abstract/IFFR.dart';
import 'package:mybase/base/abstract/IFFRefresh.dart';
import 'package:mybase/base/abstract/IFFScaffold.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/entitylog/MyApiTestRun.dart';
import 'package:mybase/base/tool/file/FFile.dart';
import 'package:mybase/base/widget/layout/FFLineContainer.dart';
import 'package:mybase/base/widget/layout/FFTextButton.dart';
import 'package:mybase/base/widget/page/FFScaffold.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:webview_window_example/config/ConfigVal.dart';
import 'package:webview_window_example/textField/FFTextField.dart';
import 'package:webview_window_example/utils/navi/AppNavi.dart';

class CreateApiPage extends FFScaffold {
  String? name;

  CreateApiPage({
    Key? key,
    this.name,
  }) : super(key: key);

  @override
  CreateApiPageState createState() => CreateApiPageState();
}

class CreateApiPageState extends FFScaffoldState with MFFScaffold {
  /**固定写法 */
  @override
  IFFScaffold get iffScaffold => this;

  @override
  CreateApiPage get widget => super.widget as CreateApiPage;

  @override
  IFFRefresh? get iffRefresh => refresh;
  late CreateApiPageRefresh refresh = CreateApiPageRefresh(state: this);

  /**固定写法end */

  String? targetFile; //比如CommonApi.dart文件
  int requestCode = 0; //0 get ，1 post
  int responseCode = 0; //0 data下是Map ，1 data下是List
  String? methodNotes; //方法注释
  String? methodName; //方法名
  String? url; //地址 例如v1.common/init
  String? entityClassName; //实体类名

  @override
  void ffInitState() {
    super.ffInitState();
  }

  @override
  Widget? ffNavi(BuildContext context) {
    return AppNavi.createNavi(
      context,
      title: "生成api调用方法",
    );
  }

  @override
  Widget? ffBody(BuildContext context) {
    return FFLineContainer(
      direction: Axis.vertical,
      children: [
        FFTextButton(
          unconstrainedBox: true,
          text: "选择方法所属的dart文件",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
          onClick: () async {
            FilePickerResult? result = await FilePicker.platform.pickFiles(
              type: FileType.custom,
              allowedExtensions: ['dart'],
              initialDirectory: ConfigVal.osDir,
            );

            if (!(await FFile.isExistFile(result?.files.single.path ?? ""))) {
              SmartDialog.showToast("目标文件选择失败");
              return;
            }

            targetFile = result!.files.single.path;
            setState(() {});
          },
        ),
        FFTextButton(
          text: targetFile,
          maxLines: 1000,
        ),
        FFLineContainer(
          direction: Axis.horizontal,
          children: [
            FFTextButton(
              unconstrainedBox: true,
              text: "GET",
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              color: requestCode == 0 ? Colors.red : Colors.grey,
              margin: EdgeInsets.only(top: 8),
              onClick: () async {
                requestCode = 0;
                setState(() {});
              },
            ),
            SizedBox(
              width: 12,
            ),
            FFTextButton(
              unconstrainedBox: true,
              text: "POST",
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              color: requestCode == 1 ? Colors.red : Colors.grey,
              margin: EdgeInsets.only(top: 8),
              onClick: () async {
                requestCode = 1;
                setState(() {});
              },
            ),
          ],
        ),
        Container(
          width: 200,
          height: 46,
          color: Colors.black,
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
          margin: EdgeInsets.only(top: 4),
          child: FFTextField(
            cursorColor: Colors.white,
            placeStr: "方法注释",
            needCancelBtn: false,
            onValid: (bool valid, String value) {
              methodNotes = value;
            },
            min: 1,
            max: 9999,
          ),
        ),
        Container(
          width: 200,
          height: 46,
          color: Colors.black,
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
          margin: EdgeInsets.only(top: 4),
          child: FFTextField(
            cursorColor: Colors.white,
            placeStr: "方法名",
            needCancelBtn: false,
            onValid: (bool valid, String value) {
              methodName = value;
            },
            min: 1,
            max: 9999,
          ),
        ),
        Container(
          width: 200,
          height: 46,
          color: Colors.black,
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
          margin: EdgeInsets.only(top: 4),
          child: FFTextField(
            cursorColor: Colors.white,
            placeStr: "地址,例如> v1.common/init",
            needCancelBtn: false,
            onValid: (bool valid, String value) {
              url = value;
            },
            min: 1,
            max: 9999,
          ),
        ),
        FFLineContainer(
          unconstrainedBox: true,
          direction: Axis.vertical,
          color: Colors.black,
          margin: EdgeInsets.only(top: 12),
          padding: EdgeInsets.only(top: 6, bottom: 6),
          children: [
            FFTextButton(
              unconstrainedBox: true,
              text: "Data直接子层是Map，List？",
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              color: Colors.yellow,
            ),
            FFLineContainer(
              direction: Axis.horizontal,
              children: [
                FFTextButton(
                  unconstrainedBox: true,
                  text: "Map",
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  color: responseCode == 0 ? Colors.red : Colors.grey,
                  margin: EdgeInsets.only(top: 2),
                  onClick: () async {
                    responseCode = 0;
                    setState(() {});
                  },
                ),
                SizedBox(
                  width: 12,
                ),
                FFTextButton(
                  unconstrainedBox: true,
                  text: "List",
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  color: responseCode == 1 ? Colors.red : Colors.grey,
                  margin: EdgeInsets.only(top: 2),
                  onClick: () async {
                    responseCode = 1;
                    setState(() {});
                  },
                ),
              ],
            ),
          ],
        ),
        Container(
          width: 200,
          height: 46,
          color: Colors.black,
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
          margin: EdgeInsets.only(top: 4),
          child: FFTextField(
            cursorColor: Colors.white,
            placeStr: "实体类名,默认TestEntity",
            needCancelBtn: false,
            onValid: (bool valid, String value) {
              entityClassName = value;
            },
            min: 1,
            max: 9999,
          ),
        ),
        FFTextButton(
          unconstrainedBox: true,
          text: "创建",
          padding: EdgeInsets.symmetric(horizontal: 14, vertical: 10),
          color: Colors.red,
          margin: EdgeInsets.only(top: 16),
          onClick: () async {
            if (!(await FFile.isExistFile(targetFile ?? ""))) {
              SmartDialog.showToast("dart文件不存在");
              return;
            }

            if (FFEmpty.stringIsEmpty(methodNotes)) {
              SmartDialog.showToast("注释必填");
              return;
            }

            if (FFEmpty.stringIsEmpty(methodName)) {
              SmartDialog.showToast("方法名必填");
              return;
            }

            if (methodName!.contains(" ")) {
              SmartDialog.showToast("方法名不能包含空格");
              return;
            }


            if (FFEmpty.stringIsEmpty(url)) {
              SmartDialog.showToast("url必填");
              return;
            }


            String templateFilePath = "";
            if (responseCode == 0) {
              templateFilePath =
                  "${ConfigVal.templateCodeDir}/TemplateApiDataMap.txt";
            } else {
              templateFilePath =
                  "${ConfigVal.templateCodeDir}/TemplateApiDataList.txt";
            }

            String result = await MyApiTestRun.createApiCodeStr(
              importHeaderFile:
                  "${ConfigVal.templateCodeDir}/TemplateImportHeader.txt",
              templateFile: templateFilePath,
              targetFile: targetFile!,

              ///文件完整路径
              methodNotes: methodNotes!,

              ///方法注释
              methodName: methodName!,

              ///方法名
              apiMethodType: requestCode == 0
                  ? "ApiUtils.GetMethod"
                  : "ApiUtils.PostMethd",

              ///请求方式
              url: url!,

              ///地址
              entityClassName: entityClassName ?? "TestEntity",
            );
            SmartDialog.showToast(result);
          },
        ),
      ],
    );
  }
}

class CreateApiPageRefresh with MFFRefresh {
  CreateApiPageState state;

  CreateApiPageRefresh({required this.state});

  @override
  bool? ffCanRefreshHead() {
    return true;
  }

  @override
  ffRefresh(bool isHead) {
    ffRefreshResult(isHead, test, state);
  }

  //具体请求业务
  Future<IFFR> test(IRefreshParam? iRefreshParam) async {
    List? list;
    await Future.wait([
      //HomeApi.index_recentlyPlayed(),
    ]).then((value) {
      list = value;
    });

    IFFR? r = list?.safeValue(0);
    return r ?? R(rStatus: RStatus.result);
  }
}
